<?php

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Tree;
use common\components\helpers\Util;
use common\models\datas\Setting;
use doumiaoduo\buildform\BuildForm;
use yii\db\Exception;
use zhtfrontend\components\services\classmanager\Createclassmanage;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\CateRelation;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\ClassManageTeacher;
use zhtfrontend\models\datas\ClassManageTime;
use zhtfrontend\models\datas\ClassroomGroup;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\GoodsPrice;
use zhtfrontend\models\datas\GoodsTeacher;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\Teacher;
use zhtfrontend\models\datas\ClassroomAttr;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\Classroom;
use yii\web\BadRequestHttpException;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
use common\models\datas\Site;
use yii\web\NotFoundHttpException;
use yii\data\Pagination;
use yii\web\Response;
use yii\helpers\Json;
use zhtfrontend\models\datas\Tutor;

class ArrangementController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = Arrangement::find()->where(['is_delete' => '0'])->andWhere(['!=', 'teaching_methods', 2])->orderBy(['classroom_id' => SORT_ASC, 'created_at' => SORT_ASC, 'teacher_id' => SORT_ASC]);
        $query = Arrangement::find()->where(['is_delete' => '0'])->andWhere(['!=', 'teaching_methods', 2])->orderBy(['classroom_id' => SORT_ASC, 'created_at' => SORT_ASC, 'teacher_id' => SORT_ASC]);
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            if (!empty($search_data['course_name'])) {
                $id = Course::find()->select('id')->where(['like', 'name', $search_data['course_name']])->column();
                $data->andWhere(['in', 'course_id', $id]);
                $query->andWhere(['in', 'course_id', $id]);
            }
            if (!empty($search_data['teacher_name'])) {
                $idS = Teacher::find()->select('id')->where(['like', 'name', $search_data['teacher_name']])->column();
                $data->andWhere(['in', 'teacher_id', $idS]);
                $query->andWhere(['in', 'teacher_id', $idS]);
            }
            if (!empty($search_data['is_booking'])) {
                if ($search_data['is_booking'] == 2) {
                    $search_data['is_booking'] = 0;
                }
                $data->andWhere(['is_booking' => $search_data['is_booking']]);
                $query->andWhere(['is_booking' => $search_data['is_booking']]);
            }
            if (!empty($search_data['mechanic_name'])) {
                $searchmids = Mechanic::find()->select('id')->where(['like', 'name', $search_data['mechanic_name']])->column();
                $searchcouresids = [];
                if ($searchmids) {
                    $searchcouresids = Course::find()->select('id')->where(['mechince_id' => $searchmids])->column();
                }
                $data->andWhere(['course_id' => $searchcouresids]);
            }
            if (!empty($search_data['class_day'])) {
                $ids = [];
                $classroom_attr_id = ClassroomAttr::find()->where(['classday' => $search_data['class_day'], 'status' => 1])->asArray()->column();
                $search = $query->asArray()->all(Fun::getSiteDb());
                if ($search != null) {
                    $search_array = ArrayHelper::map($search, 'id', 'classroom_attr_id');
                    foreach ($search_array as $k => $v) {
                        $ids_array = explode(',', $v);
                        if (!empty(array_intersect($ids_array, $classroom_attr_id))) {
                            $ids[] = $k;
                        }
                    }
                }
                $data->andWhere(['in', 'id', $ids]);
            }
        }
        //如果是机构登录
        $mids = Fun::getMechanicIds();
        if (!empty($mids)) {
            $teacherids = Teacher::find()->select('id')->where(['mechanic_id' => $mids])->column();
            $data->andWhere(['teacher_id' => $teacherids]);
        }
        //如果是业务总监登陆
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'business_director') {
            $DirectorMechanicIds = Fun::getDirectorMechanicIds();
            $courseids = Course::find()->select('id')->where(['mechince_id' => $DirectorMechanicIds])->column();
            $data->andWhere(['course_id' => $courseids]);
        }
        $data->orderBy('id DESC');
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($model, ['admin', 'booking', 'class_time', 'course_name', 'teacher_name', 'room_name', 'room_number', 'status_name', 'creategoods', 'operate']);
        return $this->render('index', ['data' => $array, 'pages' => $pages]);

    }

    public function actionCreate()
    {
        //easyui下拉表
        $mids = Fun::getMechanicIds();

        $mdelMechanic = Mechanic::find()->where(['status' => 1]);
        if ($mids) {
            $mdelMechanic->andWhere(['id' => $mids]);
        }
        $mechanic_list = $mdelMechanic->all();
        $teacher = [];
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'course_list') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $mechanic_id = \Yii::$app->request->post('mechanic_id');
            $CourseModel = Course::find()->where(['status' => 1, 'mechince_id' => $mechanic_id])->all();
            $arr = Fun::asArray($CourseModel, []);
            return $arr;
        }
        $model = new Arrangement();
        $model->scenario = 'create';
        $model->is_booking = 1;
        $model->is_online = 1;
        $model->is_group = 0;

        $classprice = [];

        //当点击老师的时候
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'th') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $course_id = \Yii::$app->request->post('course_id');

            $course = Course::findOne($course_id);

            $teacherIds = CateRelation::find()->select('object_id')->where(['cate_id' => $course->category_id, 'type' => 1])->column();
            $classroomIds = CateRelation::find()->select('object_id')->where(['cate_id' => $course->category_id, 'type' => 2])->column();
            $teacherList = Teacher::find()->where(['id' => $teacherIds, 'status' => 1])->all();
            $classroom = Classroom::find()->select(['id', 'name', 'room_number', 'max_count', 'type'])->where(['id' => $classroomIds, 'state' => 1, 'is_share' => 0])->all();
            $roomGroup = ClassroomGroup::find()->asArray()->all();
            if ($roomGroup) {
                foreach ($roomGroup as $k => $group) {
                    $room = Classroom::find()->where(['classroom_group_id' => $group['id']])->asArray()->all();
                    if (!empty($room)) {
                        $roomGroup[$k]['room'] = $room;
                    } else {
                        unset($roomGroup[$k]);
                    }
                }
            }
//            print_r($roomGroup);die;
            $data['teacher'] = $teacherList;
            $data['classroom'] = $classroom; //普通教室
            $data['roomGroup'] = $roomGroup; //普通教室
            return $data;

        }
        //当点击搜索机构的时候
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'search_mechanic') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $name = \Yii::$app->request->post('name');
            $modelMechanic = Mechanic::find()->where(['status'=>1]);
            if ($mids) {
                $modelMechanic->andWhere(['id' => $mids]);
            }
            if ($name != null) {
                $modelMechanic->andWhere(['like', 'name', $name]);
            }
            $data = $modelMechanic->all();
            //$arr = Fun::asArray($data, ['mechanic_name']);
            return $data;

        }

        //判断一天的课次
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'classCount') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $class_count = \Yii::$app->request->post('class_count');
            $ids = \Yii::$app->request->post('ids');
            $attrids = explode(',', $ids);
            $classday = ClassroomAttr::find()->select('classday')->where(['id' => $attrids])->column();
            $number = array_count_values($classday);
            $content = '';
            $max = floor($class_count / 3);
            foreach ($number as $v) {
                if ($v > $max) {
                    $content = $class_count . '节课，一天的上课次数不能大于' . $max . '节课';
                    break;
                }
            }
            $data['data'] = $content;
            return $data;
        }
        //ajax联动
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'cc') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $classroom_id = \Yii::$app->request->post('classroom_id');
            $course_id = \Yii::$app->request->post('course_id');
            $room_type = \Yii::$app->request->post('room_type');

            if ($classroom_id == null || $course_id == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
            }
            if ($room_type == 1) {
                $classroom_id = Classroom::find()->select('id')->where(['state' => 1, 'classroom_group_id' => $classroom_id])->column();
            }
            $model = ClassroomAttr::find()->where(['classroom_id' => $classroom_id])->asArray()->all();
            if ($model != null) {
                foreach ($model as $k => $v) {
                    $len = strlen($v['end_time']) - 2;
                    $length = strlen($v['start_time']) - 2;
                    $classIds = ClassManageTime::find()->select('class_id')->where(['classroom_attr_id' => $v['id']])->groupBy('class_id')->column();
//                    $goods_ids = GoodsClassTime::find()->select('goods_id')->where(['classroom_attr_id'=>$v['id']])->column();
                    $c1 = ClassManage::find()->where(['is_old' => 0, 'status' => [0, 1], 'class_id' => $classIds])->count();
//                    $arrang = Arrangement::find()->where(['classroom_id'=>$classroom_id,'is_online'=>1])->all();
//                    $arr = [];
//                    foreach($arrang as $arrs){
//                        if(!empty($arrs->classroom_attr_id)) {
//                            $e = explode(',', $arrs->classroom_attr_id);
//                            if(in_array($v['id'],$e)){
//                                $arr[] = $arrs->id;
//                            }
//                        }
//                    }
//                    $c2= ClassManage::find()->where(['is_old'=>1,'status'=>[0,1],'associate_id'=>$arr])->count();
//                    $co = $c1+$c2;
                    $model[$k]['classday'] = Util::getWeek($v['classday']);
                    $model[$k]['start_time'] = floor($v['start_time'] / 100) . ':' . substr($v['start_time'], $length);
                    $model[$k]['end_time'] = floor($v['end_time'] / 100) . ':' . substr($v['end_time'], $len);
                    $model[$k]['count'] = $c1;
                }
                $data['data'] = $model;
                return $data;
            } else {
                return [];
            }
        }

        //获取价格
        $setclassprice = Setting::find()->where(['key' => 'classprice'])->one();
        if ($setclassprice != null && !empty($setclassprice['value'])) {
            $value = unserialize($setclassprice['value']);
            $price = explode(',', $value['class_price']);
            foreach ($price as $p) {
                if (!empty($p))
                    $classprice[$p] = $p;
            }
        }
        $classcount = [];
        //获取课次
        $setclasscount = Setting::find()->where(['key' => 'classcount'])->one();
        if ($setclasscount != null && !empty($setclasscount['value'])) {
            $value = unserialize($setclasscount['value']);
            $count = explode(',', $value['class_count']);
            foreach ($count as $c) {
                if (!empty($c))
                    $classcount[$c] = $c;
            }
        }

        //获取导师
        $tutorModel = Teacher::find()->where(['is_tutor' => 1])->all();
        $tutor = ArrayHelper::map($tutorModel, 'id', 'name');


        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        //arrange_class表，classroom_attr表
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {

            //print_r(\Yii::$app->request->post());die;

            $first_attr_id = explode(',', $model->classroom_attr_id);
            $classroomattr = ClassroomAttr::findone($first_attr_id[0]);
            if ($classroomattr == null) {
                throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
            } else {
                $coures = Course::findOne($model->course_id);
                $model->admin_id = \Yii::$app->user->id;
                $model->is_delete = 0;
                $model->suitable_age = '';
                $model->teaching_methods = 1;
                $model->mechanic_id = $coures->mechince_id;
                $model->category_id = $coures->type_id;
                if (!empty($model->min_age) && !empty($model->max_age)) {
                    $str = ',';
                    $arr = range($model->min_age, $model->max_age);
                    if (count($arr) == 1) {
                        $str .= $arr[0] . ',';
                    } else {
                        foreach ($arr as $age) {
                            $str .= $age . ',';
                        }
                    }
                    $model->suitable_age = $str;
                    $model->age_group = $model->min_age . '-' . $model->max_age;
                }
                $start_second = (int)substr($classroomattr->start_time, 2);
                $end_second = (int)substr($classroomattr->end_time, 2);
                if (strlen($classroomattr->start_time) == 3) {
                    $start_second = (int)substr($classroomattr->start_time, 1);
                }
                if (strlen($classroomattr->end_time) == 3) {
                    $end_second = (int)substr($classroomattr->end_time, 1);
                }

                $model->class_length = (floor($classroomattr->end_time / 100) - floor($classroomattr->start_time / 100)) * 60 + ($end_second - $start_second);
                if ($model->save(false)) {
//                    $this->SyncGoods($model);
                    return \Yii::$app->response->redirect(Fun::url(['arrangement/success']));
                }
            }
            return \Yii::$app->response->redirect(Fun::url(['arrangement/index']));
        }
        return $this->render('create', ['mechanicList' => $mechanic_list, 'teacher' => $teacher, 'model' => $model, 'classprice' => $classprice, 'classcount' => $classcount, 'tutor' => $tutor]);
    }

    public function actionUpdate()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '请求错误'));
        }
        $act = \Yii::$app->request->get('act');
        $model = Arrangement::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'update';
        $model->price = floor($model->price);
        if (!empty($model->suitable_age)) {
            $arrGae = substr($model->suitable_age, 1, -1);
            $arr = explode(',', $arrGae);
            $model->min_age = $arr[0];
            $model->max_age = $arr[count($arr) - 1];
        }
        $mids = Fun::getMechanicIds();

        $mdelMechanic = Mechanic::find()->where(['status' => 1]);
        if ($mids) {
            $mdelMechanic->andWhere(['id' => $mids]);
        }
        $mechanic_list = $mdelMechanic->all();
        $teacher = [];
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'course_list') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $mechanic_id = \Yii::$app->request->post('mechanic_id');
            $CourseModel = Course::find()->where(['status' => 1, 'mechince_id' => $mechanic_id])->all();
            $arr = Fun::asArray($CourseModel, []);
            return $arr;
        }

        $classprice = [];

        //当点击老师的时候
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'th') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $course_id = \Yii::$app->request->post('course_id');

            $course = Course::findOne($course_id);

            $teacherIds = CateRelation::find()->select('object_id')->where(['cate_id' => $course->category_id, 'type' => 1])->column();
            $classroomIds = CateRelation::find()->select('object_id')->where(['cate_id' => $course->category_id, 'type' => 2])->column();
            $teacherList = Teacher::find()->where(['id' => $teacherIds, 'status' => 1])->all();
            $classroom = Classroom::find()->select(['id', 'name', 'room_number', 'max_count', 'type'])->where(['id' => $classroomIds, 'state' => 1, 'is_share' => 0])->all();
            $roomGroup = ClassroomGroup::find()->asArray()->all();
            if ($roomGroup) {
                foreach ($roomGroup as $k => $group) {
                    $room = Classroom::find()->where(['classroom_group_id' => $group['id']])->asArray()->all();
                    if (!empty($room)) {
                        $roomGroup[$k]['room'] = $room;
                    } else {
                        unset($roomGroup[$k]);
                    }
                }
            }
//            print_r($roomGroup);die;
            $data['teacher'] = $teacherList;
            $data['classroom'] = $classroom; //普通教室
            $data['roomGroup'] = $roomGroup; //普通教室
            return $data;

        }

        //当点击搜索机构的时候
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'search_mechanic') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $name = \Yii::$app->request->post('name');
            $modelMechanic = Mechanic::find()->where(['status'=>1]);
            if ($mids) {
                $modelMechanic->andWhere(['id' => $mids]);
            }
            if ($name != null) {
                $modelMechanic->andWhere(['like', 'name', $name]);
            }
            $data = $modelMechanic->all();
            return $data;

        }
        //当点击老师的时候
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'search_teacher') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $name = \Yii::$app->request->post('name');
            $teacherModel = Teacher::find()->where(['status' => 1, 'site_id' => Fun::getSiteId()]);
            if ($mids) {
                $teacherModel->andWhere(['mechanic_id' => $mids]);
            }
            if ($name != null) {
                $teacherModel->andWhere(['like', 'name', $name]);
            }
            $teacher = $teacherModel->all();
            $arr = Fun::asArray($teacher, ['mechanic_name']);
            return $arr;

        }

        //判断一天的课次
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'classCount') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $class_count = \Yii::$app->request->post('class_count');
            $ids = \Yii::$app->request->post('ids');
            $attrids = explode(',', $ids);
            $classday = ClassroomAttr::find()->select('classday')->where(['id' => $attrids])->column();
            $number = array_count_values($classday);
            $content = '';
            $max = floor($class_count / 3);
            foreach ($number as $v) {
                if ($v > $max) {
                    $content = $class_count . '节课，一天的上课次数不能大于' . $max . '节课';
                    break;
                }
            }
            $data['data'] = $content;
            return $data;
        }
        //ajax联动
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'cc') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $classroom_id = \Yii::$app->request->post('classroom_id');
            $course_id = \Yii::$app->request->post('course_id');
            $room_type = \Yii::$app->request->post('room_type');

            if ($classroom_id == null || $course_id == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
            }
            if ($room_type == 1) {
                $classroom_id = Classroom::find()->select('id')->where(['state' => 1, 'classroom_group_id' => $classroom_id])->column();
            }
            $model = ClassroomAttr::find()->where(['classroom_id' => $classroom_id])->asArray()->all();
            if ($model != null) {
                foreach ($model as $k => $v) {
                    $len = strlen($v['end_time']) - 2;
                    $length = strlen($v['start_time']) - 2;
                    $classIds = ClassManageTime::find()->select('class_id')->where(['classroom_attr_id' => $v['id']])->groupBy('class_id')->column();
//                    $goods_ids = GoodsClassTime::find()->select('goods_id')->where(['classroom_attr_id'=>$v['id']])->column();
                    $c1 = ClassManage::find()->where(['is_old' => 0, 'status' => [0, 1], 'class_id' => $classIds])->count();
//                    $arrang = Arrangement::find()->where(['classroom_id'=>$classroom_id,'is_online'=>1])->all();
//                    $arr = [];
//                    foreach($arrang as $arrs){
//                        if(!empty($arrs->classroom_attr_id)) {
//                            $e = explode(',', $arrs->classroom_attr_id);
//                            if(in_array($v['id'],$e)){
//                                $arr[] = $arrs->id;
//                            }
//                        }
//                    }
//                    $c2= ClassManage::find()->where(['is_old'=>1,'status'=>[0,1],'associate_id'=>$arr])->count();
//                    $co = $c1+$c2;
                    $model[$k]['classday'] = Util::getWeek($v['classday']);
                    $model[$k]['start_time'] = floor($v['start_time'] / 100) . ':' . substr($v['start_time'], $length);
                    $model[$k]['end_time'] = floor($v['end_time'] / 100) . ':' . substr($v['end_time'], $len);
                    $model[$k]['count'] = $c1;
                }
                $data['data'] = $model;
                return $data;
            } else {
                return [];
            }
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        //获取价格
        $setclassprice = Setting::find()->where(['key' => 'classprice'])->one();
        if ($setclassprice != null && !empty($setclassprice['value'])) {
            $value = unserialize($setclassprice['value']);
            $price = explode(',', $value['class_price']);
            foreach ($price as $p) {
                if (!empty($p))
                    $classprice[$p] = $p;
            }
        }
        $classcount = [];
        //获取课次
        $setclasscount = Setting::find()->where(['key' => 'classcount'])->one();
        if ($setclasscount != null && !empty($setclasscount['value'])) {
            $value = unserialize($setclasscount['value']);
            $count = explode(',', $value['class_count']);
            foreach ($count as $c) {
                if (!empty($c))
                    $classcount[$c] = $c;
            }
        }

        //获取导师
        $tutorModel = Teacher::find()->where(['is_tutor' => 1])->all();
        $tutor = ArrayHelper::map($tutorModel, 'id', 'name');
        //arrange_class表，classroom_attr表
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $first_attr_id = explode(',', $model->classroom_attr_id);
            $classroomattr = ClassroomAttr::findone($first_attr_id[0]);
            if ($classroomattr == null) {
                throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
            } else {
                $start_second = (int)substr($classroomattr->start_time, 2);
                $end_second = (int)substr($classroomattr->end_time, 2);
                if (strlen($classroomattr->start_time) == 3) {
                    $start_second = (int)substr($classroomattr->start_time, 1);
                }
                if (strlen($classroomattr->end_time) == 3) {
                    $end_second = (int)substr($classroomattr->end_time, 1);
                }
                $suitable_age = '';
                $age_group = '';
                if (!empty($model->min_age) && !empty($model->max_age)) {
                    $str = ',';
                    $arr = range($model->min_age, $model->max_age);
                    if (count($arr) == 1) {
                        $str .= $arr[0] . ',';
                    } else {
                        foreach ($arr as $age) {
                            $str .= $age . ',';
                        }
                    }
                    $suitable_age = $str;
                    $age_group = $model->min_age . '-' . $model->max_age;
                }
                $coures = Course::findOne($model->course_id);
                $model->admin_id = \Yii::$app->user->id;
                $model->suitable_age = $suitable_age;
                $model->age_group = $age_group;
                $model->mechanic_id = $coures->mechince_id;
                $model->category_id = $coures->type_id;
                $model->class_length = (floor($classroomattr->end_time / 100) - floor($classroomattr->start_time / 100)) * 60 + ($end_second - $start_second);
                if ($model->save(false)) {
//                        $this->SyncGoods($model);
                    return \Yii::$app->response->redirect(Fun::url(['arrangement/success']));
                }

            }
            return \Yii::$app->response->redirect(Fun::url(['arrangement/index']));
        }
        return $this->render('create', ['mechanicList' => $mechanic_list, 'model' => $model, 'classprice' => $classprice, 'classcount' => $classcount, 'tutor' => $tutor]);
    }


    public function actionCopy()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '请求错误'));
        }
        $model = Arrangement::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'update';
        $model->price = floor($model->price);
        if (!empty($model->suitable_age)) {
            $arrGae = substr($model->suitable_age, 1, -1);
            $arr = explode(',', $arrGae);
            $model->min_age = $arr[0];
            $model->max_age = $arr[count($arr) - 1];
        }
        $mids = Fun::getMechanicIds();

        $mdelMechanic = Mechanic::find()->where(['status' => 1]);
        if ($mids) {
            $mdelMechanic->andWhere(['id' => $mids]);
        }
        $mechanic_list = $mdelMechanic->all();
        $teacher = [];
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'course_list') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $mechanic_id = \Yii::$app->request->post('mechanic_id');
            $CourseModel = Course::find()->where(['is_artteaching' => 0, 'status' => 1, 'mechince_id' => $mechanic_id])->all();
            $arr = Fun::asArray($CourseModel, []);
            return $arr;
        }

        $classprice = [];

        //当点击老师的时候
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'th') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $course_id = \Yii::$app->request->post('course_id');

            $course = Course::findOne($course_id);

            $teacherIds = CateRelation::find()->select('object_id')->where(['cate_id' => $course->category_id, 'type' => 1])->column();
            $classroomIds = CateRelation::find()->select('object_id')->where(['cate_id' => $course->category_id, 'type' => 2])->column();
            $teacherList = Teacher::find()->where(['id' => $teacherIds, 'status' => 1])->all();
            $classroom = Classroom::find()->select(['id', 'name', 'room_number', 'max_count', 'type'])->where(['id' => $classroomIds, 'state' => 1, 'is_share' => 0])->all();
            $roomGroup = ClassroomGroup::find()->asArray()->all();
            if ($roomGroup) {
                foreach ($roomGroup as $k => $group) {
                    $room = Classroom::find()->where(['classroom_group_id' => $group['id']])->asArray()->all();
                    if (!empty($room)) {
                        $roomGroup[$k]['room'] = $room;
                    } else {
                        unset($roomGroup[$k]);
                    }
                }
            }
//            print_r($roomGroup);die;
            $data['teacher'] = $teacherList;
            $data['classroom'] = $classroom; //普通教室
            $data['roomGroup'] = $roomGroup; //普通教室
            return $data;

        }
        //当点击老师的时候
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'search_teacher') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $name = \Yii::$app->request->post('name');
            $teacherModel = Teacher::find()->where(['status' => 1, 'site_id' => Fun::getSiteId()]);
            if ($mids) {
                $teacherModel->andWhere(['mechanic_id' => $mids]);
            }
            if ($name != null) {
                $teacherModel->andWhere(['like', 'name', $name]);
            }
            $teacher = $teacherModel->all();
            $arr = Fun::asArray($teacher, ['mechanic_name']);
            return $arr;

        }

        //判断一天的课次
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'classCount') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $class_count = \Yii::$app->request->post('class_count');
            $ids = \Yii::$app->request->post('ids');
            $attrids = explode(',', $ids);
            $classday = ClassroomAttr::find()->select('classday')->where(['id' => $attrids])->column();
            $number = array_count_values($classday);
            $content = '';
            $max = floor($class_count / 3);
            foreach ($number as $v) {
                if ($v > $max) {
                    $content = $class_count . '节课，一天的上课次数不能大于' . $max . '节课';
                    break;
                }
            }
            $data['data'] = $content;
            return $data;
        }
        //ajax联动
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'cc') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $classroom_id = \Yii::$app->request->post('classroom_id');
            $course_id = \Yii::$app->request->post('course_id');
            $room_type = \Yii::$app->request->post('room_type');

            if ($classroom_id == null || $course_id == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
            }
            if ($room_type == 1) {
                $classroom_id = Classroom::find()->select('id')->where(['state' => 1, 'classroom_group_id' => $classroom_id])->column();
            }
            $model = ClassroomAttr::find()->where(['classroom_id' => $classroom_id])->asArray()->all();
            if ($model != null) {
                foreach ($model as $k => $v) {
                    $len = strlen($v['end_time']) - 2;
                    $length = strlen($v['start_time']) - 2;
                    $classIds = ClassManageTime::find()->select('class_id')->where(['classroom_attr_id' => $v['id']])->groupBy('class_id')->column();
//                    $goods_ids = GoodsClassTime::find()->select('goods_id')->where(['classroom_attr_id'=>$v['id']])->column();
                    $c1 = ClassManage::find()->where(['is_old' => 0, 'status' => [0, 1], 'class_id' => $classIds])->count();
//                    $arrang = Arrangement::find()->where(['classroom_id'=>$classroom_id,'is_online'=>1])->all();
//                    $arr = [];
//                    foreach($arrang as $arrs){
//                        if(!empty($arrs->classroom_attr_id)) {
//                            $e = explode(',', $arrs->classroom_attr_id);
//                            if(in_array($v['id'],$e)){
//                                $arr[] = $arrs->id;
//                            }
//                        }
//                    }
//                    $c2= ClassManage::find()->where(['is_old'=>1,'status'=>[0,1],'associate_id'=>$arr])->count();
//                    $co = $c1+$c2;
                    $model[$k]['classday'] = Util::getWeek($v['classday']);
                    $model[$k]['start_time'] = floor($v['start_time'] / 100) . ':' . substr($v['start_time'], $length);
                    $model[$k]['end_time'] = floor($v['end_time'] / 100) . ':' . substr($v['end_time'], $len);
                    $model[$k]['count'] = $c1;
                }
                $data['data'] = $model;
                return $data;
            } else {
                return [];
            }
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        //获取价格
        $setclassprice = Setting::find()->where(['key' => 'classprice'])->one();
        if ($setclassprice != null && !empty($setclassprice['value'])) {
            $value = unserialize($setclassprice['value']);
            $price = explode(',', $value['class_price']);
            foreach ($price as $p) {
                if (!empty($p))
                    $classprice[$p] = $p;
            }
        }
        $classcount = [];
        //获取课次
        $setclasscount = Setting::find()->where(['key' => 'classcount'])->one();
        if ($setclasscount != null && !empty($setclasscount['value'])) {
            $value = unserialize($setclasscount['value']);
            $count = explode(',', $value['class_count']);
            foreach ($count as $c) {
                if (!empty($c))
                    $classcount[$c] = $c;
            }
        }

        //获取导师
        $tutorModel = Tutor::find()->where(['status' => 1])->all();
        $tutor = ArrayHelper::map($tutorModel, 'id', 'name');
        //arrange_class表，classroom_attr表
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $first_attr_id = explode(',', $model->classroom_attr_id);
            $classroomattr = ClassroomAttr::findone($first_attr_id[0]);
            if ($classroomattr == null) {
                throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
            } else {
                $start_second = (int)substr($classroomattr->start_time, 2);
                $end_second = (int)substr($classroomattr->end_time, 2);
                if (strlen($classroomattr->start_time) == 3) {
                    $start_second = (int)substr($classroomattr->start_time, 1);
                }
                if (strlen($classroomattr->end_time) == 3) {
                    $end_second = (int)substr($classroomattr->end_time, 1);
                }
                $suitable_age = '';
                $age_group = '';
                if (!empty($model->min_age) && !empty($model->max_age)) {
                    $str = ',';
                    $arr = range($model->min_age, $model->max_age);
                    if (count($arr) == 1) {
                        $str .= $arr[0] . ',';
                    } else {
                        foreach ($arr as $age) {
                            $str .= $age . ',';
                        }
                    }
                    $suitable_age = $str;
                    $age_group = $model->min_age . '-' . $model->max_age;
                }
                $coures = Course::findOne($model->course_id);
                $newArrangement = new Arrangement();
                $newArrangement->course_id = $model->course_id;
                $newArrangement->teacher_id = $model->teacher_id;
                $newArrangement->classroom_id = $model->classroom_id;
                $newArrangement->classroom_attr_id = $model->classroom_attr_id;
                $newArrangement->class_length = (floor($classroomattr->end_time / 100) - floor($classroomattr->start_time / 100)) * 60 + ($end_second - $start_second);
                $newArrangement->class_count = $model->class_count;
                $newArrangement->max_number = $model->max_number;
                $newArrangement->opening_number = $model->opening_number;
                $newArrangement->is_booking = $model->is_booking;
                $newArrangement->booking_count = $model->booking_count;
                $newArrangement->booking_price = $model->booking_price;
                $newArrangement->admin_id = \Yii::$app->user->id;
                $newArrangement->price = $model->price;
                $newArrangement->cost = $model->price;
                $newArrangement->cost = $model->price;
                $newArrangement->market_price = $model->market_price;
                $newArrangement->is_online = $model->is_online;
                $newArrangement->suitable_age = $suitable_age;
                $newArrangement->teaching_methods = $model->teaching_methods;
                $newArrangement->is_group = $model->is_group;
                $newArrangement->category_id = $coures->type_id;
                $newArrangement->tutor_id = $model->tutor_id;
                $newArrangement->mechanic_id = $coures->mechince_id;
                $newArrangement->age_group = $age_group;
                if ($newArrangement->save(false)) {
                    return \Yii::$app->response->redirect(Fun::url(['arrangement/success']));
                }

            }
            return \Yii::$app->response->redirect(Fun::url(['arrangement/index']));
        }
        return $this->render('create', ['mechanicList' => $mechanic_list, 'model' => $model, 'classprice' => $classprice, 'classcount' => $classcount, 'tutor' => $tutor]);
    }


    public function actionSuccess()
    {
        return $this->render('success');
    }

    public function actionTeachercreate()
    {
        $this->layout = false;
        $mids = Fun::getMechanicIds(); //获取机构以及子机构id
        $site = Site::findOne(['id' => Fun::getSiteId()]);
        $model = new Teacher();
        $model->scenario = 'create';
        $model->status = 1;
        $form = new BuildForm('@app/components/forms/teacherForm.php');
        $form->loadModel(['teacher' => $model]);
        $form->loadDefaultValues();
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0, 'status' => 1]);
        if (!empty($mids)) {
            $mechanicModel->andWhere(['id' => $mids]);//这个地方是如果是有机构id传过来，那么可以选择的有当前的机构或者是找个机构的子类
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        if (count($mechanic) == 1) {
            foreach ($mechanic as $key => $val) {
                $model->mechanic_id = $key;
            }
        }
        $tree_mechanic = (new Tree($mechanic))->get_tree_select();
        $form->setItems('teacher', 'mechanic_id', $tree_mechanic);
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $model->site_id = Fun::getSiteId();
            $model->isrecommend = 0;
            if (empty($model->mobile) && $model->status == 1) {
                $model->mobile = $this->generateRandAccount();
            }
            if ($model->is_headmaster == 1) {
                $model->headmaster_account = $this->generateRandAccount('h', 'headmaster_account');
            }
            if ($model->save(false)) {
                return $this->redirectMessage('添加成功', Fun::url(['arrangement/create']));
            }
        }
        return $this->render('teachercreate', ['mode' => $site->mode, 'form' => $form->render()]);
    }

    public function generateRandAccount($s = 't', $field = 'mobile')
    {
        $string = range(0, 9);
        for ($i = 1; $i <= 5; $i++) {
            $key = rand(0, 9);
            $s .= $string[$key];
        }
        $teacher = Teacher::find()->where(['like', $field, $s])->one(Fun::getSiteDb());
        if ($teacher !== null) {
            $this->generateRandAccount();
        }
        return $s;
    }

    public function actionDelete()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Arrangement::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->is_delete = 1;
        if ($model->save(false)) {
            return $this->redirectMessage(\Yii::t('zhtfrontend', '删除成功'), Fun::url(['arrangement/index']));
        }
    }

    /**
     * 生成班级
     * @param $arrangement
     */
    public function actionCreatemanage()
    {
        if (\Yii::$app->request->isAjax) {
            $return = ['status' => 0, 'content' => ''];
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $id = \Yii::$app->request->get('id');
            if ($id == null) {
                $return = ['status' => 0, 'content' => '请求错误'];
                return $return;
            }

            $model = Arrangement::findOne($id);
            if ($model == null) {
                $return = ['status' => 0, 'content' => '请求错误'];
                return $return;
            }
            $classroom_name = isset($model->classroom->name) ? $model->classroom->name : '';
            $classroom_id = $model->classroom_id;
            $room_group_id = 0;
            $classroom_group__name = '';
            if ($model->room_type == 1) {
                $classroom_group__name = isset($model->classroomgroup->name) ? $model->classroomgroup->name : '';
                $classroom_id = 0;
                $room_group_id = $model->classroom_id;
                $classroom_name = '';
            }
            $transaction = Fun::getSiteDb()->beginTransaction();
            $classAttr = ClassManageAttribute::find()->where(['arrangement_id' => $id])->one();
            try {
                if ($classAttr == null) {
                    $modelClassManage = new ClassManage();
                    $modelClassManage->mechanic_id = isset($model->course->mechince_id) ? $model->course->mechince_id : 0;
                    $modelClassManage->class_code = 'c' . time();
                    $modelClassManage->code = $model->id;
                    $modelClassManage->is_book = $model->is_booking;
                    $modelClassManage->is_old = 0;
                    if ($model->is_online == 0) {
                        $modelClassManage->is_old = 1;
                        $modelClassManage->associate_id = $model->id;
                    }
                    if ($modelClassManage->save(false)) {
                        //生成班级属性
                        $modelClassManageAttr = new ClassManageAttribute();
                        $modelClassManageAttr->class_id = $modelClassManage->class_id;
                        $modelClassManageAttr->course_id = $model->course_id;
                        $modelClassManageAttr->course = isset($model->course->name) ? $model->course->name : '';
//                        $modelClassManageAttr->teacher_id = $model->teacher_id;
//                        $modelClassManageAttr->teacher = isset($model->teacher->name) ? $model->teacher->name : '';
                        $modelClassManageAttr->room_id = $classroom_id;
                        $modelClassManageAttr->classroom_name = $classroom_name;
                        $modelClassManageAttr->classroom_number = $model->room_type == 0 ? !empty($model->classroom) ? $model->classroom->room_number : '' : '';
                        $modelClassManageAttr->teacher_form = isset($model->course->teache_form) ? $model->course->teache_form : 0;
                        $modelClassManageAttr->price = $model->price;
                        $modelClassManageAttr->class_count = $model->class_count;
                        $modelClassManageAttr->suitable_age = $model->suitable_age;
                        $modelClassManageAttr->age_group = $model->age_group;
                        $modelClassManageAttr->class_length = $model->class_length;
                        $modelClassManageAttr->max_number = $model->max_number;
                        $modelClassManageAttr->opening_number = $model->opening_number;
                        $modelClassManageAttr->is_booking = $model->is_booking;
                        $modelClassManageAttr->region = '李沧区';
                        $modelClassManageAttr->tutor_id = $model->tutor_id;
                        $modelClassManageAttr->is_group = $model->is_group;
                        $modelClassManageAttr->arrangement_id = $model->id;
                        $modelClassManageAttr->room_group_id = $room_group_id;
                        $modelClassManageAttr->room_group_name = $classroom_group__name;
                        $modelClassManageAttr->room_type = $model->room_type;
                        $modelClassManageAttr->updated_at = $model->updated_at;
                        $modelClassManageAttr->save(false);

                        //生成班级上课时间
                        if (!empty($model->classroom_attr_id)) {
                            $timeArr = explode(',', $model->classroom_attr_id);
                            $classroom_attr = ClassroomAttr::find()->where(['id' => $timeArr])->all();
                            if ($classroom_attr != null) {
                                foreach ($classroom_attr as $k => $v) {
                                    $modelClassManageTime = new ClassManageTime();
                                    $modelClassManageTime->class_id = $modelClassManage->class_id;
                                    $modelClassManageTime->class_day = $v->classday;
                                    $len = strlen($v->start_time);
                                    $length = strlen($v->end_time);
                                    if ($len == 1) {
                                        $start_hour = '00';
                                        $start_minute = '0' . $v->start_time;
                                    } elseif ($len == 2) {
                                        $start_hour = '00';
                                        $start_minute = $v->start_time;
                                    } elseif ($len == 3) {
                                        $start_hour = '0' . floor($v->start_time / 100);
                                        $start_minute = substr($v->start_time, 1);
                                    } else {
                                        $start_hour = floor($v->start_time / 100);
                                        $start_minute = substr($v->start_time, 2);
                                    }
                                    if ($length == 1) {
                                        $end_hour = '00';
                                        $end_minute = '0' . $v->end_time;
                                    } elseif ($length == 2) {
                                        $end_hour = '00';
                                        $end_minute = $v->start_time;
                                    } elseif ($length == 3) {
                                        $end_hour = '0' . floor($v->end_time / 100);
                                        $end_minute = substr($v->end_time, 1);
                                    } else {
                                        $end_hour = floor($v->end_time / 100);
                                        $end_minute = substr($v->end_time, 2);
                                    }
                                    $start_time = $start_hour . ':' . $start_minute;
                                    $end_time = $end_hour . ':' . $end_minute;
                                    $modelClassManageTime->start_time = $start_time;
                                    $modelClassManageTime->end_time = $end_time;
                                    $modelClassManageTime->classroom_attr_id = $v->id;
                                    $modelClassManageTime->save(false);
                                }
                            }
                        }
                        if (!empty($model->teacher_id)) {
                            $teacherArr = explode(',', $model->teacher_id);
                            foreach ($teacherArr as $id) {
                                $modelTeacher = Teacher::findOne($id);
                                $modelClassteacher = new ClassManageTeacher();
                                $modelClassteacher->class_id = $modelClassManage->class_id;
                                $modelClassteacher->teacher_id = $id;
                                $modelClassteacher->teacher_name = $modelTeacher->name;
                                $modelClassteacher->save(false);
                            }
                        }
                        $content = '生成成功！';
                    }
                } else {
                    $classAttr->course_id = $model->course_id;
                    $classAttr->course = isset($model->course->name) ? $model->course->name : '';
                    $classAttr->teacher_id = $model->teacher_id;
                    $classAttr->teacher = isset($model->teacher->name) ? $model->teacher->name : '';
                    $classAttr->room_id = $model->classroom_id;
                    $classAttr->classroom_name = $classroom_name;
                    $classAttr->classroom_number = isset($model->classroom->room_number) ? $model->classroom->room_number : '';
                    $classAttr->teacher_form = isset($model->course->teache_form) ? $model->course->teache_form : 0;
                    $classAttr->price = $model->price;
                    $classAttr->class_count = $model->class_count;
                    $classAttr->suitable_age = $model->suitable_age;
                    $classAttr->age_group = $model->age_group;
                    $classAttr->class_length = $model->class_length;
                    $classAttr->max_number = $model->max_number;
                    $classAttr->opening_number = $model->opening_number;
                    $classAttr->is_booking = $model->is_booking;
                    $classAttr->region = '李沧区';
                    $classAttr->tutor_id = $model->tutor_id;
                    $classAttr->is_group = $model->is_group;
                    $classAttr->room_group_id = $room_group_id;
                    $classAttr->room_group_name = $classroom_group__name;
                    $classAttr->room_type = $model->room_type;
                    $classAttr->updated_at = $model->updated_at;
                    $classAttr->save(false);

                    if (!empty($model->classroom_attr_id)) {
                        $timeArr = explode(',', $model->classroom_attr_id);
                        $classroom_attr = ClassroomAttr::find()->where(['id' => $timeArr])->all();
                        if ($classroom_attr != null) {
                            ClassManageTime::deleteAll(['class_id' => $classAttr->class_id]);
                            foreach ($classroom_attr as $k => $v) {
                                $modelClassManageTime = new ClassManageTime();
                                $modelClassManageTime->class_id = $classAttr->class_id;
                                $modelClassManageTime->class_day = $v->classday;
                                $len = strlen($v->start_time);
                                $length = strlen($v->end_time);
                                if ($len == 1) {
                                    $start_hour = '00';
                                    $start_minute = '0' . $v->start_time;
                                } elseif ($len == 2) {
                                    $start_hour = '00';
                                    $start_minute = $v->start_time;
                                } elseif ($len == 3) {
                                    $start_hour = '0' . floor($v->start_time / 100);
                                    $start_minute = substr($v->start_time, 1);
                                } else {
                                    $start_hour = floor($v->start_time / 100);
                                    $start_minute = substr($v->start_time, 2);
                                }
                                if ($length == 1) {
                                    $end_hour = '00';
                                    $end_minute = '0' . $v->end_time;
                                } elseif ($length == 2) {
                                    $end_hour = '00';
                                    $end_minute = $v->start_time;
                                } elseif ($length == 3) {
                                    $end_hour = '0' . floor($v->end_time / 100);
                                    $end_minute = substr($v->end_time, 1);
                                } else {
                                    $end_hour = floor($v->end_time / 100);
                                    $end_minute = substr($v->end_time, 2);
                                }
                                $start_time = $start_hour . ':' . $start_minute;
                                $end_time = $end_hour . ':' . $end_minute;
                                $modelClassManageTime->start_time = $start_time;
                                $modelClassManageTime->end_time = $end_time;
                                $modelClassManageTime->classroom_attr_id = $v->id;
                                $modelClassManageTime->save(false);
                            }
                        }
                    }
                    if (!empty($model->teacher_id)) {
                        ClassManageTeacher::deleteAll(['class_id' => $classAttr->class_id]);
                        $teacherArr = explode(',', $model->teacher_id);
                        foreach ($teacherArr as $id) {
                            $modelTeacher = Teacher::findOne($id);
                            $modelClassteacher = new ClassManageTeacher();
                            $modelClassteacher->class_id = $classAttr->class_id;
                            $modelClassteacher->teacher_id = $id;
                            $modelClassteacher->teacher_name = $modelTeacher->name;
                            $modelClassteacher->save(false);
                        }
                    }
                    $content = '更新成功！';
                }
                $transaction->commit();
                $return = ['status' => 1, 'content' => $content];
                return $return;
            } catch (\Exception $e) {
                $return = ['status' => 0, 'content' => '操作失败！'];
                return $return;
            }
        }
    }

    public function actionSyncgoods()
    {
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $id = \Yii::$app->request->get('id');
            if ($id == null) {
                return ['status' => 0, 'content' => '系统错误刷新页面重试'];
            }
            $arrangement = Arrangement::findOne($id);
            $transaction = Fun::getSiteDb()->beginTransaction();
            try {
                $is_shelve = 0;
                $status = 0;
                $is_update_price = 1;
                $price_arr = [];
                $manageGoods = null;
                $oldGoods = Goods::find()->where(['arrangement_id' => $arrangement->id, 'is_delete' => 0])->one();
                if ($oldGoods != null) {
                    $is_shelve = $oldGoods->is_shelve;
                    $status = $oldGoods->status;
                    $is_update_price = $oldGoods->is_update_price;
                    $oldGoods->is_shelve = 0;
                    $oldGoods->is_delete = 1;
                    $oldGoods->save(false);
                    $price_arr = GoodsPrice::find()->where(['goods_id' => $oldGoods->id])->asArray()->all();
                    $manageGoods = ClassManageGoods::find()->where(['goods_id' => $oldGoods->id])->one();
                }
                $goods = new Goods();
                $goods_name = isset($arrangement->course) ? $arrangement->course->name : '';
                $goods->name = $goods_name;
                $goods->sn = 'course' . time();
                $goods->cat_id = isset($arrangement->course) ? $arrangement->course->category_id : '';
                $goods->type_id = 1;
                $goods->price = $arrangement->price;
                $goods->market_price = $arrangement->market_price;
                $goods->store = $arrangement->max_number;
                $goods->picture = isset($arrangement->teacher) ? $arrangement->teacher->img : '';
                $goods->description = isset($arrangement->teacher) ? $arrangement->teacher->description : '';
                $goods->content = isset($arrangement->course) ? $arrangement->course->description : '';
                $goods->site_id = Fun::getSiteId();
                $goods->mechanic_id = isset($arrangement->teacher) ? $arrangement->teacher->mechanic_id : isset($arrangement->course) ? $arrangement->course->mechince_id : '';
                $goods->goods_type = 'normal';
                $goods->max_buy = 1;
                $goods->store_prompt = 5;
                $goods->score = 0;
                $goods->is_shelve = $is_shelve;
                $goods->is_delete = 0;
                $goods->is_buy = 1;
                $goods->teaching_methods = $arrangement->teaching_methods;
                $goods->is_group = $arrangement->is_group;
                $goods->category_id = $arrangement->category_id;
                $goods->arrangement_id = $arrangement->id;
                $goods->tutor_id = $arrangement->tutor_id;
                $goods->admin_id = \Yii::$app->user->id;
                $goods->up_at = time();
                $goods->updated_at = $arrangement->updated_at;
                $goods->status = $status;
                $goods->is_update_price = $is_update_price;
                if ($goods->save(false)) {

                    //同步上课时间
                    if (!empty($arrangement->classroom_attr_id)) {
                        $timeArr = explode(',', $arrangement->classroom_attr_id);
                        $classroom_attr = ClassroomAttr::find()->where(['id' => $timeArr])->all();
                        if ($classroom_attr != null) {
                            foreach ($classroom_attr as $k => $v) {
                                $modelGoodsTime = new GoodsClassTime();
                                $modelGoodsTime->goods_id = $goods->id;
                                $modelGoodsTime->class_day = $v->classday;
                                $len = strlen($v->start_time);
                                $length = strlen($v->end_time);
                                if ($len == 1) {
                                    $start_hour = '00';
                                    $start_minute = '0' . $v->start_time;
                                } elseif ($len == 2) {
                                    $start_hour = '00';
                                    $start_minute = $v->start_time;
                                } elseif ($len == 3) {
                                    $start_hour = '0' . floor($v->start_time / 100);
                                    $start_minute = substr($v->start_time, 1);
                                } else {
                                    $start_hour = floor($v->start_time / 100);
                                    $start_minute = substr($v->start_time, 2);
                                }
                                if ($length == 1) {
                                    $end_hour = '00';
                                    $end_minute = '0' . $v->end_time;
                                } elseif ($length == 2) {
                                    $end_hour = '00';
                                    $end_minute = $v->start_time;
                                } elseif ($length == 3) {
                                    $end_hour = '0' . floor($v->end_time / 100);
                                    $end_minute = substr($v->end_time, 1);
                                } else {
                                    $end_hour = floor($v->end_time / 100);
                                    $end_minute = substr($v->end_time, 2);
                                }
                                $start_time = $start_hour . ':' . $start_minute;
                                $end_time = $end_hour . ':' . $end_minute;
                                $modelGoodsTime->start_time = $start_time;
                                $modelGoodsTime->end_time = $end_time;
                                $modelGoodsTime->classroom_attr_id = $v->id;
                                $modelGoodsTime->room_id = $arrangement->classroom_id;
                                $modelGoodsTime->save(false);
                            }
                        }
                    }
                    //同步老师
                    if (!empty($arrangement->teacher_id)) {
                        $teacherArr = explode(',', $arrangement->teacher_id);
                        foreach ($teacherArr as $id) {
                            $modelTeacher = Teacher::findOne($id);
                            $modelGoodsteacher = new GoodsTeacher();
                            $modelGoodsteacher->goods_id = $goods->id;
                            $modelGoodsteacher->teacher_id = $id;
                            $modelGoodsteacher->teacher_name = $modelTeacher->name;
                            $modelGoodsteacher->save(false);
                        }
                    }

                    //如果价格存在保存价格
                    if (!empty($price_arr)) {
                        foreach ($price_arr as $price) {
                            $goods_price = new GoodsPrice();
                            $goods_price->goods_id = $goods->id;
                            $goods_price->price_name = $price['price_name'];
                            $goods_price->lesson = $price['lesson'];
                            $goods_price->lesson_price = $price['lesson_price'];
                            $goods_price->distribution_way = $price['distribution_way'];
                            $goods_price->distribution_proportion = $price['distribution_proportion'];
                            $goods_price->subsidy_type = $price['subsidy_type'];
                            $goods_price->subsidy_money = $price['subsidy_money'];
                            $goods_price->is_scholarship = $price['is_scholarship'];
                            $goods_price->scholarship = $price['scholarship'];
                            $goods_price->admin_id = $price['admin_id'];
                            $goods_price->status = $price['status'];
                            $goods_price->created_at = $price['created_at'];
                            $goods_price->market_price = $price['market_price'];
                            $goods_price->activity_name = $price['activity_name'];
                            $goods_price->is_activity = $price['is_activity'];
                            $goods_price->activity_start_time = $price['activity_start_time'];
                            $goods_price->activity_end_time = $price['activity_end_time'];
                            $goods_price->effective_number = $price['effective_number'];
                            $goods_price->is_frequency = $price['is_frequency'];
                            $goods_price->deadline_type = $price['deadline_type'];
                            $goods_price->deadline = $price['deadline'];
                            $goods_price->back_status = $price['back_status'];
                            $goods_price->price = $price['price'];
                            $goods_price->save(false);
                        }
                    }
                    //此课程如果已生成班级
                    if ($manageGoods != null) {
                        Createclassmanage::update($goods->id, $manageGoods->class_id);
                    }


                    //同步goods_attr
                    $filed = ['class_length' => ['name' => '上课时长', 'obj_type' => 'class_length',],
                        'max_number' => ['name' => '最满人数', 'obj_type' => 'max_number'],
                        'opening_number' => ['name' => '开课人数', 'obj_type' => 'opening_number'],
                    ];
                    //给课程保存的时候添加一个地区属性
                    $mechanic = Mechanic::findOne(['id' => $goods->mechanic_id]);
                    $attributes = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $mechanic['id'], 'name' => '地域', 'value' => isset($mechanic->region) ? $mechanic->region : '', 'obj_type' => 'region']);
                    $attributes->save(false);
                    $arrange = $arrangement->toArray([], ['course_name', 'teacher_name', 'room_number', 'room_name', 'teacher_form']);
                    foreach ($arrange as $k => $v) {
                        if (in_array($k, ['course_id', 'classroom_id', 'class_length', 'max_number', 'opening_number', 'is_booking', 'teacher_form', 'suitable_age', 'age_group'])) {
                            if ($k == 'course_id') {
                                $attributes = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $v, 'name' => '课程', 'value' => $arrange['course_name'], 'obj_type' => 'course']);
                                $attributes->save(false);
                            } elseif ($k == 'classroom_id') {
                                $attributes = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $v, 'name' => '教室编号', 'value' => $arrange['room_number'], 'obj_type' => 'classroom_number']);
                                $attributes->save(false);

                                if ($arrange['room_type'] == 1) {
                                    $classroom_name = '1-' . $arrange['group_room_name'];
                                } else {
                                    $classroom_name = '0-' . $arrange['room_name'];
                                }

                                $attributes_1 = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $v, 'name' => '教室名称', 'value' => $classroom_name, 'obj_type' => 'classroom_name']);
                                $attributes_1->save(false);
                            } elseif ($k == 'is_booking') {
                                $attributes = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $arrange['id'], 'name' => '是否可预约', 'value' => $v, 'obj_type' => 'is_booking']);
                                $attributes->save(false);
                            } elseif ($k == 'teacher_form') {
                                $attributes = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $v, 'name' => '授课方式', 'value' => $arrange['teacher_form'], 'obj_type' => 'teacher_form']);
                                $attributes->save(false);
                            } elseif ($k == 'suitable_age') {
                                if (!empty($arrange['suitable_age'])) {
                                    $attributes = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $arrange['id'], 'name' => '适合年龄段', 'value' => $arrange['suitable_age'], 'obj_type' => $k]);
                                    $attributes->save(false);
                                }
                            } elseif ($k == 'age_group') {//年龄段
                                if (!empty($arrange['age_group'])) {
                                    $attributes = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $arrange['id'], 'name' => '年龄段', 'value' => $arrange['age_group'], 'obj_type' => $k]);
                                    $attributes->save(false);
                                }
                            } else {
                                $attributes = new GoodsAttr(['goods_id' => $goods->id, 'attribute_id' => $arrange['id'], 'name' => $filed[$k]['name'], 'value' => $v, 'obj_type' => $filed[$k]['obj_type']]);
                                $attributes->save(false);
                            }
                        }
                    }

                }
                $transaction->commit();
                return ['status' => 1, 'content' => '生成商品成功'];
            } catch (Exception $e) {
                $transaction->rollBack();
                return ['status' => 0, 'content' => '生成商品失败'];
            }
        }
    }

    public function SyncClassManage($arrangement)
    {

        $classManage = ClassManage::findOne(['associate_id' => $arrangement->id, 'is_old' => 1]);
        if ($classManage == null) {
            $teacher_mechanic = Teacher::findone([$arrangement->teacher_id]);
            $classManage = new ClassManage();
            $classManage->class_code = "c" . time();
            $classManage->headmaster = 0;
            $classManage->pclass_id = 0;
            $classManage->is_book = 0;
            $classManage->is_old = 1;
            $classManage->associate_id = $arrangement->id;
            $classManage->mechanic_id = $teacher_mechanic != null ? $teacher_mechanic->mechanic_id : '';
            if ($classManage->save(false)) {
                return 1;
            } else {
                return 0;
            }
        } else {
            return 1;
        }
    }
    public function actionBuygrade(){
        $model = [];
        $this->render('buygrade',['model'=>$model]);
    }

}